//
//  FuncHelper.swift
//  Md5Compare
//
//  Created by mx004 on 17/11/24.
//  Copyright © 2017年 mx004. All rights reserved.
//

import Foundation
/// (obsolete) 获取指定文件夹下的所有文件名
/// - parameter path: 文件夹路径
/// - returns: 所有文件名数组
func findFiles(_ path: String) -> [String] {
    var files = [String]()
    let fileManager = FileManager.default
    let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: path)!
    while let element = enumerator.nextObject() as? String {
        
        if (element as NSString).lastPathComponent == ".DS_Store" {
            continue
        }
        if element.range(of: ".svn") != nil {
            continue
        }
        var isDir: ObjCBool = true
        let fullPath = "\(path)/\(element)"
        fileManager.fileExists(atPath: fullPath, isDirectory: &isDir)
        if isDir.boolValue {
            continue
        }
        
        files.append(fullPath)
    }
    return files
}

let fileManager = FileManager.default;
func md5File(_ path:String) -> String? {
    
    if !FileManager.default.fileExists(atPath: path) {
        return nil
    }
    
    let data2 = fileManager.contents(atPath: path)
    let rs = String(data:data2!,encoding:String.Encoding.utf8)
    return rs?.md5()
}

func fileMd5(_ path: String) -> String? {
    
    let handle = FileHandle(forReadingAtPath: path)
    
    if handle == nil {
        return nil
    }
    
    let ctx = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: MemoryLayout<CC_MD5_CTX>.size)
    
    CC_MD5_Init(ctx)
    
    var done = false
    
    while !done {
        let fileData = handle?.readData(ofLength: 256)
        
        fileData?.withUnsafeBytes {(bytes: UnsafePointer<CChar>)->Void in
            //Use `bytes` inside this closure
            //...
            CC_MD5_Update(ctx, bytes, CC_LONG(fileData!.count))
        }
        
        if fileData?.count == 0 {
            done = true
        }
    }
    
    //unsigned char digest[CC_MD5_DIGEST_LENGTH];
    let digestLen = Int(CC_MD5_DIGEST_LENGTH)
    let digest = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
    CC_MD5_Final(digest, ctx);
    
    var hash = ""
    for i in 0..<digestLen {
        hash +=  String(format: "%02x", (digest[i]))
    }
    
    digest.deinitialize()
    ctx.deinitialize()
    
    return hash;
    
}

